from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
from md5 import get_password_hash
from .models import Users, Roles


class LoginSerializers(ModelSerializer):
    username = serializers.CharField(max_length=128)

    class Meta:
        model = Users
        fields = ["username", "password"]


class UserSerializers(ModelSerializer):
    role_ids = serializers.ListField(child=serializers.IntegerField(), write_only=True)
    created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = Users
        fields = ["id", "username", "phone", "password", "email", "nickname", "description", "created_at", "updated_at",
                  "last_login", "role_ids"]
        read_only_fields = ["id", "last_login"]
        write_only_fields = ["password", "role_ids"]
        extra_kwargs = {
            'description': {"required": False},
        }

    def validate(self, attrs):
        password = attrs.get('password')
        attrs["password"] = get_password_hash(password)
        return attrs

    def validate_role_ids(self, item):
        for role_id in item:
            if role_id == 1:
                raise ValidationError("无法对超级管理员进行操作")
            role = Roles.objects.filter(id=role_id).first()
            if not role:
                raise ValidationError("角色不存在")
        return item
